import React, { useState } from 'react';
import { ArrowLeft, Microphone, MicrophoneMute } from '@nutui/icons-react';
import { Button, Input } from '@nutui/nutui-react';
import './MyRentalHousing.css';
import { useEffect } from 'react';

// 判断浏览器是否支持语音识别
const hasSpeechRecognition = 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window;

export default function MyRentalHousing() {
  // 定义消息列表的状态
  const [messages, setMessages] = useState([]);
  // 定义输入框的值的状态
  const [inputValue, setInputValue] = useState('');
  // 定义是否正在加载的状态
  const [isLoading, setIsLoading] = useState(false);
  // 定义麦克风是否禁用状态
  const [isMicrophoneMuted, setIsMicrophoneMuted] = useState(false);

  // 处理发送消息
  const handleSendMessage = async () => {
    if (inputValue.trim()!== '') {
      const newMessage = { role: 'user', content: inputValue };
      setMessages([...messages, newMessage]);
      setInputValue('');
      setIsLoading(true);

      try {
        const response = await fetch('http://localhost:3000/jwh/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ messages: [newMessage] }),
        });

        if (response.ok) {
          const data = await response.json();
          const aiResponseContent = data.result;
          let displayedContent = '';
          const interval = setInterval(() => {
            if (displayedContent.length < aiResponseContent.length) {
              displayedContent = aiResponseContent.slice(0, displayedContent.length + 1);
              const aiResponse = { role: 'assistant', content: displayedContent };
              setMessages([...messages, newMessage, aiResponse]);
            } else {
              clearInterval(interval);
              setIsLoading(false);
            }
          }, 100);
        } else {
          console.error('Error fetching AI response');
          setIsLoading(false);
        }
      } catch (error) {
        console.error('Error:', error);
        setIsLoading(false);
      }
    }
  };

  // 处理输入框的值的变化
  const handleInputChange = (event) => {
    setInputValue(event);
  };

  // 处理麦克风图标点击事件
  const handleMicrophoneClick = () => {
    setIsMicrophoneMuted(!isMicrophoneMuted);
    if (hasSpeechRecognition) {
      if (!isMicrophoneMuted) {
        startSpeechRecognition();
      } else {
        stopSpeechRecognition();
      }
    }
  };

  // 开始语音识别
  const startSpeechRecognition = () => {
    if (hasSpeechRecognition) {
      const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
      recognition.lang = 'zh-CN';
      recognition.continuous = false; // 设置为连续识别
      recognition.interimResults = true; // 设置为返回临时结果
      recognition.timeout = 10000; // 设置超时时间，单位为毫秒
      

      recognition.onresult = (event) => { 
        const transcript = event.results[0][0].transcript;
        setInputValue(transcript);
      };

      recognition.start();
    } else {
      console.log('语音输入不支持');
    }
  };

  // 停止语音识别
  const stopSpeechRecognition = () => {
    if (hasSpeechRecognition) {
      const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
      recognition.stop();
    }
  };

  return (
    <div>
      <div className='MyHouse'>
        <div className='MyHouse_top'>
          <ArrowLeft className="back-icon" width={"40px"} onClick={() => window.history.back()} />
          <span className="title-text">AI 服务</span>
        </div>
        <div className='MyHouse_content'>
          <div className="chat-container">
            <div className="chat-messages">
              {messages.map((message, index) => (
                <div key={index} className={`chat-message ${message.role}`} style={{ fontSize: '14px' }}>
                  {message.content}
                </div>
              ))}
              {isLoading && (
                <div style={{ textAlign: 'center', marginTop: '10px', color: '#17d56b' }}>回复中...</div>
              )}
            </div>
            <div className="chat-input">
              {!isMicrophoneMuted? (
                <MicrophoneMute
                  style={{ position: 'absolute', zIndex: '21', top: '23px', right: '102px' }}
                  onClick={handleMicrophoneClick}
                />
              ) : (
                <Microphone
                  style={{ position: 'absolute', zIndex: '20', top: '23px', right: '102px' }}
                  onClick={handleMicrophoneClick}
                />
              )}
              <Input
                placeholder="输入消息..."
                value={inputValue}
                onChange={handleInputChange}
                style={{ borderRadius: '8px', border: '1px solid #ccc', padding: '8px', height: '30px' }}
              />
              <Button
                type="primary"
                style={{ borderRadius: '8px', backgroundColor: '#007BFF', color: '#fff', padding: '8px 16px', height: '30px' }}
                onClick={handleSendMessage}
              >发送</Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}